package com.dingwen.treasure.security.config;

import cn.hutool.core.util.ArrayUtil;
import com.dingwen.treasure.security.exception.TreasureAuthenticationEntryPoint;
import com.dingwen.treasure.security.filter.JwtAuthenticationTokenFilter;
import com.dingwen.treasure.security.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import javax.annotation.Resource;

/**
 * 　SecurityConfig: Spring Security 配置参考若依实现 </br>
 *  <ol>
 *      <li>@EnableWebSecurity： 启用 spring security</li>
 *      <li>@EnableGlobalMethodSecurity 开启基于方法的认证，方法前认证</li>
 *  </ol>
 *  // TODO 验证码过滤器、基于数据库的记住我实现，认证、授权异常BUG
 *  // TODO 在满足GET放行的情况下POST也放行了
 * 　@author dingwen
 * 　@date 2022/6/12
 */
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置项
     */
    @Resource
    private SecurityProperties properties;

    /**
     * 用户认证服务
     */
    @Resource
    private UserDetailsService userDetailsService;


    /**
     * 访问权限不符合异常处理返回
     */
    @Resource
    private TreasureAuthenticationEntryPoint treasureAuthenticationEntryPoint;

    /**
     * tokenService
     */
    @Resource
    private TokenService tokenService;


    /**
     * 解决session失效后 sessionRegistry中session没有同步失效的问题
     */
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }


    /**
     * 密码编码器
     */
    @Bean
    protected BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置用户认证
     *
     * @param auth 认证
     * @throws Exception 例外
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return {@link AuthenticationManager}
     * @throws Exception 例外
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问 (登录以后不能访问)
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 启用跨域配置
                .cors()
                .and()
                // 禁用 CSRF
                .csrf().disable()
                // 异常处理
                .exceptionHandling()
                .authenticationEntryPoint(treasureAuthenticationEntryPoint)
                .and()

                // 禁用表单登录 自行实现
                .formLogin().disable()
                // 禁用httpBasic
                .httpBasic().disable()
                // 禁用登出 自行实现
                .logout().disable()
                // 开始定义认证请求
                .authorizeRequests()
                // 允许匿名访问的
                .antMatchers(ArrayUtil.toArray(properties.getAnonymous(), String.class)).anonymous()
                // 放行 请求 GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
                .antMatchers(ArrayUtil.toArray(properties.getIgnores(), String.class)).permitAll()
                .antMatchers(HttpMethod.OPTIONS, ArrayUtil.toArray(properties.getOptions(), String.class)).permitAll()
                .antMatchers(HttpMethod.GET, ArrayUtil.toArray(properties.getGet(), String.class)).permitAll()
                .antMatchers(HttpMethod.POST, ArrayUtil.toArray(properties.getPost(), String.class)).permitAll()
                .antMatchers(HttpMethod.PUT, ArrayUtil.toArray(properties.getPut(), String.class)).permitAll()
                .antMatchers(HttpMethod.DELETE, ArrayUtil.toArray(properties.getDelete(), String.class)).permitAll()
                .antMatchers(HttpMethod.HEAD, ArrayUtil.toArray(properties.getHead(), String.class)).permitAll()
                .antMatchers(HttpMethod.TRACE, ArrayUtil.toArray(properties.getTrace(), String.class)).permitAll()
                // 所有的请求 都需要认证
                .anyRequest().authenticated()
                // 所有的请求都放行
                //.anyRequest().permitAll()

                // 使用JWT, 禁止session
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 自定义过滤器
                .and()
                // 认证过滤器
                // 此处注意： 若将过滤器交由Spring管理则会导致在Security放行等URI仍然会进过滤器
                .addFilterBefore(new JwtAuthenticationTokenFilter(tokenService),
                        UsernamePasswordAuthenticationFilter.class);
    }


    /**
     * 配置放行接口不进入 security 的过滤器链 （否则security放行接口仍然会进入过滤器）
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) {
        // 匹配以下URI (URL + URN) 不过 security 过滤器链
        web.ignoring()
                .antMatchers(ArrayUtil.toArray(properties.getAnonymous(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getIgnores(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getGet(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getPost(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getPut(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getOptions(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getDelete(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getTrace(), String.class))
                .antMatchers(ArrayUtil.toArray(properties.getHead(), String.class));
    }

}
